
<!DOCTYPE HTML>
<html>
<head>
    <meta charset="UTF-8">
    <title>消息中心</title>
</head>

<body>
WebSocket<br/>
<input id="text" type="text" placeholder="消息"/>
<input id="target" type="text" placeholder="发送目标"/>
<button onclick="send()">发送消息</button>
<button onclick="closeWebSocket()">关闭</button>
<div id="message">
</div>
</body>

<script type="text/javascript">
    var websocket = null;
    var userId = null;
    var targetId = null;

    //判断当前浏览器是否支持WebSocket
    if('WebSocket' in window){
        this.userId = prompt("输入userId");
        this.targetId = prompt("输入targetId");
        this.websocket = new WebSocket("ws://huangrui.vaiwan.com/ws/"+this.userId+"/"+this.targetId);
    }
    else{
        alert('Not support websocket')
    }

    //连接成功建立的回调方法
    websocket.onopen = function(event){
        setMessageInnerHTML("连接建立成功");
    }

    //连接发生错误的回调方法
    websocket.onerror = function(){
        setMessageInnerHTML("连接发生错误");
    };

    //接收到消息的回调方法
    websocket.onmessage = function(event){
        var message = JSON.parse(event.data);
        if (message.type == 3){
            setMessageInnerHTML("对方已屏蔽您的消息。");
        }else if(message.type == 4){
            setMessageInnerHTML("对方不接收商品分享");
        }
        else{
            setMessageInnerHTML("来自："+message.sender+" 消息："+message.content);
        }
    }

    //连接关闭的回调方法
    websocket.onclose = function(){
        setMessageInnerHTML("连接关闭");
    }

    //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
    window.onbeforeunload = function(){
        websocket.close();
    }

    //将消息显示在网页上
    function setMessageInnerHTML(innerHTML){
        document.getElementById('message').innerHTML += innerHTML + '<br/>';
    }

    //关闭连接
    function closeWebSocket(){
        websocket.close();
    }

    //发送消息
    function send(){
        var text = document.getElementById('text').value;
        var target = parseInt(document.getElementById('target').value);
        var message = {}
        message['type'] = prompt("消息类型: 1正常 2商品分享");
        message['target'] = target;
        message['content'] = text;
        websocket.send(JSON.stringify(message));
        setMessageInnerHTML(text);
    }

    //发送商品
    function sendProduct(){
        var text = "{\"product\":\"商品名ssssssssssss\"}";
        var target = parseInt(document.getElementById('target').value);
        var message = {}
        message['type'] = 1;
        message['target'] = target;
        message['content'] = text;
        websocket.send(JSON.stringify(message));
        setMessageInnerHTML(text);
    }

    function showSendMessage(datetime, status){
        if (status===0){
            setMessageInnerHTML(datetime+"发送成功");
        } else if (status===1) {
            setMessageInnerHTML(datetime+"发送成功，等待对方上线");
        }
    }
</script>
</html>
